<template>
  <l-content :app="app" width="1600px" v-loading="loading">
    <el-card body-style="padding: 0" class="card-bottom-spacing">
      <div slot="header" class="card-title">
        订单信息
      </div>
      <el-row type="flex">
        <el-col :span="16" style="border-right: 1px solid #ebeef5;">
          <div style="padding: 20px">
            <el-row type="flex" class="msg-row">
              <el-col :span="8">
                <span class="msg-label">本地订单号：</span>
                <span class="msg-content">{{detail.localOrderId}}</span>
              </el-col>
              <el-col :span="7">
                <span class="msg-label">订单来源：</span>
                <span class="msg-content">{{detail.shopName}}</span>
              </el-col>
              <el-col :span="9">
                <span class="msg-label">预订方式：</span>
                <span class="msg-content">{{detail.bookWayStr}}</span>
              </el-col>
            </el-row>
            <el-row type="flex" class="msg-row">
              <el-col :span="8">
                <span class="msg-label">网店出票单号：</span>
                <span class="msg-content">{{detail.issueBillId}}</span>
              </el-col>
              <el-col :span="7">
                <span class="msg-label">航司订单号：</span>
                <span class="msg-content">{{detail.airlineOrderId}}</span>
              </el-col>
              <el-col :span="9">
                <span class="msg-label">政策类型：</span>
                <span class="msg-content">{{detail.policyTypeStr}}</span>
              </el-col>
            </el-row>
            <el-row type="flex" class="msg-row">
              <el-col :span="8">
                <span class="msg-label">PNR：</span>
                <span class="msg-content">{{detail.recordNo}}</span>
                <c-copy :text="detail.recordNo"/>/
                <span class="msg-content">{{detail.airlineRecordNo}}</span>
                <c-copy :text="detail.airlineRecordNo"/>
              </el-col>
              <el-col :span="7">
                <span class="msg-label">原PNR：</span>
                <span class="msg-content">{{detail.oldPnr}}</span>/
                <span class="msg-content">{{detail.oldAirlineRecordNo}}</span>
                <span class="msg-content"><el-button type="text" v-if="detail.oldPnr" @click="onCancelPNR">取消</el-button></span>
              </el-col>
              <el-col :span="9">
                <span class="msg-label">政策代码：</span>
                <span class="msg-content">{{detail.policyCode}}</span>
                <c-copy :text="detail.policyCode"/>
                <c-mark-policy :code="detail.policyCode" :options="options.policyCodeMark"/>
              </el-col>
            </el-row>
            <el-row type="flex" class="msg-row">
              <el-col :span="24">
                <span class="msg-label">匹配政策：</span>
                <span class="font-red">{{detail.issueRemark}}</span>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :span="8">
          <div style="padding: 20px">
            <div style="line-height: 60px;font-size: 24px;text-align: center" class="font-orange">
              {{detail.orderStatusStr}}
            </div>
            <div class="msg-row">
              <template v-if="isThawFailed">
                <span class="msg-span">
                  <span class="msg-label">锁单人：</span>
                  <span class="msg-content">{{detail.lockOperatorName}}</span>
                </span>
                <span class="msg-span">
                  <span class="msg-label">锁单时间：</span>
                  <span class="msg-content">{{detail.lockTime | datetimeShortFormat2}}</span>
                </span>
              </template>
              <template v-if="canUnlock">
                <span class="msg-span">
                <span class="msg-label">锁单人：</span>
                <span class="msg-content">{{detail.lockOperatorName}}</span>
              </span>
                <span class="msg-span">
                <span class="msg-label">锁单时间：</span>
                <span class="msg-content">{{detail.lockTime | datetimeShortFormat2}}</span>
              </span>
                <span class="msg-span">
                已锁单<span class="font-red">{{lockTime}}</span>
              </span>
                <easy-button size="mini" type="success" @click="onUnlock">解锁</easy-button>
              </template>
              <template v-else-if="canLock">
                <easy-button size="mini" type="primary" @click="onLock">锁单</easy-button>
              </template>
            </div>
            <div class="msg-row">
              <span class="msg-span">
                <span class="msg-label"> 最晚出票时间：</span>
                <span>{{detail.lastPrintTicketTime | datetimeShortFormat1}}</span>
              </span>
              <span class="msg-span" v-if="showUrgency">
                <span class="msg-label"> 剩余：</span>
              <span class="font-red" style="font-size: 18px;font-weight: bold;">{{detail.lastPrintTicketTime | leaveTimeFilter}}</span>
              </span>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="card-bottom-spacing">
      <div slot="header" class="card-title">
        行程信息
      </div>
      <div class="trip-row" v-for="(item, idx) in detail.tripInfoList" :key="idx">
        <div class="trip-part-1">
          <span class="trip-mark">{{idx + 1}}</span>
        </div>
        <div class="trip-part-2">
          <div class="trip-content">
            <span class="font-red">{{item.takeOffTime | datetimeShortFormat1}}</span>
            <span>{{item.dCityStr}}({{item.dCity}})</span>
            <span>--{{item.dPortStr}}（{{item.dPort}}）</span>
          </div>
        </div>
        <div class="trip-part-3">
          <i class="fa fa-plane"></i>
        </div>
        <div class="trip-part-2">
          <div class="trip-content">
            <span class="font-red">{{item.arrivalTime | datetimeShortFormat1}}</span>
            <span>{{item.aCityStr}}({{item.aCity}})</span>
            <span>--{{item.aPortStr}}（{{item.aPort}}）</span>
          </div>
        </div>
        <div class="trip-part-5">
          <span>航班号：</span><span class="font-red">{{item.flight}}</span>
        </div>
        <div class="trip-part-6">
          <span>舱位：</span><span class="font-red">{{item.subClass}}</span><span>{{item.clazz | cabinFilter}}</span>
        </div>
        <div class="trip-part-7">
          <el-popover
            title="退改签规定"
            width="200"
            trigger="click"
            :content="detail.eiRemark">
            <el-button type="text" slot="reference">查看退改签</el-button>
          </el-popover>
        </div>
      </div>
    </el-card>

    <el-card class="card-bottom-spacing">
      <div slot="header" class="card-title">
        乘机人信息
        <span style="margin-left: 40px;display: inline-block">
          <easy-button :disabled="disabled" v-if="canSetTicketNo" size="mini" type="primary" @click="onSetTicketNo">获取票号</easy-button>
          <easy-button :disabled="disabled" v-if="canDismantle" size="mini" type="primary" @click="onDismantle">拆单</easy-button>
        </span>
      </div>
      <el-form ref="passengerList" :model="detail" size="mini">
        <el-table
          :summary-method="getSummaries"
          :data="detail.passengerList"
          border
          show-summary
          @selection-change="selectRows = $event"
          class="el-easy-ui-table">
          <el-table-column
            type="selection"
            width="30">
          </el-table-column>
          <el-table-column
            label="序号"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            label="乘机人"
            min-width="180">
            <template slot-scope="scope">
              <div :title="scope.row.passengerMobile">
                {{scope.row.passengerName}}
                <span class="mark-adult" v-if="scope.row.ageType === 'ADU'">成</span>
                <span class="mark-child" v-if="scope.row.ageType === 'CHI'">童</span>
                <span class="mark-baby" v-if="scope.row.ageType === 'BAB'">婴</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="cardNo"
            label="证件号"
            min-width="160">
          </el-table-column>
          <el-table-column
            prop="ticketNoAll"
            label="票号"
            min-width="140">
            <template slot-scope="scope">
              <el-form-item :prop="'passengerList[' + scope.$index + '].ticketNoAll'" :rules="rules.ticketNo">
                <el-input placeholder="xxx-xxxxxxxxxx" :value="scope.row.ticketNoAll" @input="onInputTicketNo(scope.$index, $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="purchasePrintPrice"
            label="采购票面价"
            min-width="90">
            <template slot-scope="scope">
              <el-input size="mini" :value="scope.row.purchasePrintPrice" @input="v => {
              scope.row.purchasePrintPrice = v
              scope.row.purchasePrice = v ? fixed2(v * (1 - (scope.row.agencyRate||0))):''
              scope.row.issueProfit = v? fixed2(scope.row.salePrice - scope.row.purchasePrice):''
            }"/>
            </template>
            <el-input></el-input>
          </el-table-column>
          <el-table-column
            label="代理费率"
            min-width="100">
            <template slot-scope="scope">
              <c-percent-input size="mini" :value="scope.row.agencyRate" @input="v => {
              scope.row.agencyRate = v
              scope.row.agencyFixedFee = v ? fixed2(parseFloat(v) * scope.row.purchasePrintPrice) : ''
              scope.row.purchasePrice = fixed2(scope.row.purchasePrintPrice - (scope.row.agencyFixedFee||0))
              scope.row.issueProfit = fixed2(scope.row.salePrice - scope.row.purchasePrice)
            }"/>
            </template>
          </el-table-column>
          <el-table-column
            label="代理费"
            min-width="80">
            <template slot-scope="scope">
              <el-input size="mini" :value="scope.row.agencyFixedFee" @input="v => {
              scope.row.agencyFixedFee = v
              scope.row.agencyRate = v ? fixed4(v / scope.row.purchasePrintPrice) : ''
              scope.row.purchasePrice = fixed2(scope.row.purchasePrintPrice - (scope.row.agencyFixedFee||0))
              scope.row.issueProfit = fixed2(scope.row.salePrice - scope.row.purchasePrice)
            }"/>
            </template>
          </el-table-column>
          <el-table-column
            label="采购价"
            min-width="90">
            <template slot-scope="scope">
              <el-input size="mini" :value="scope.row.purchasePrice" @input="v => {
              scope.row.purchasePrice = v
              scope.row.agencyFixedFee = v?fixed2(scope.row.purchasePrintPrice - v):''
              scope.row.agencyRate = v?fixed4(scope.row.agencyFixedFee / scope.row.purchasePrintPrice) : ''
              scope.row.issueProfit = fixed2(scope.row.salePrice - scope.row.purchasePrice)
            }"/>
            </template>
          </el-table-column>
          <el-table-column
            prop="saleProfit"
            label="让利"
            min-width="90">
          </el-table-column>
          <el-table-column
            prop="salePrice"
            label="销售价"
            min-width="90">
          </el-table-column>
          <el-table-column
            prop="tax"
            label="税+费"
            min-width="80">
            <template slot-scope="scope">
              {{+(scope.row.tax || 0)}}+{{+(scope.row.oilFee) || 0}}
            </template>
          </el-table-column>
          <!--<el-table-column-->
          <!--label="服务费"-->
          <!--width="90">-->
          <!--<template slot-scope="scope">-->
          <!--<el-input v-model="scope.row.serviceFee" size="mini"/>-->
          <!--</template>-->
          <!--</el-table-column>-->
          <!--<el-table-column-->
          <!--prop="insuranceFee"-->
          <!--label="保险"-->
          <!--width="90">-->
          <!--</el-table-column>-->
          <el-table-column
            prop="issueProfit"
            label="出票利润"
            min-width="90">
          </el-table-column>
          <el-table-column
            prop="saleTotalPrice"
            label="应收金额"
            min-width="90">
          </el-table-column>
          <el-table-column
            prop="passengerMobile"
            label="手机号"
            min-width="120">
          </el-table-column>
        </el-table>
      </el-form>
    </el-card>
    <el-card class="card-bottom-spacing">
      <div slot="header" class="card-title">
        出票信息
      </div>
      <el-tabs v-if="canOnlineIssue" v-model="activeTicketTab" type="border-card" style="margin: 0 0 15px;">
        <el-tab-pane label="在线出票" name="online">
          <!-- 等加载完才能渲染 -->
          <online-draw-ticket :disabled="disabled" ref="onlineDrawTicket" v-if="loaded" :issueTicket="operator.issueTicket" :detail="detail" @issueTicket="checkIsOutStatus"/>
        </el-tab-pane>
        <el-tab-pane label="线下出票" name="offline">
          <el-form ref="offlineIssueForm" inline label-width="100px" size="mini" :model="detail" :rules="rules">
            <template v-if="activeTicketTab === 'offline'">
              <div>
                <el-form-item label="出票渠道" prop="issueChannel">
                  <el-select v-model="detail.issueChannel" class="w160">
                    <el-option v-for="item in options.issueChannel" :value="item.key" :key="item.key" :label="item.cname"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="出票方" v-if="issueChannel === 'B2C'">
                  <el-select v-model="detail.issueType" class="w160">
                    <el-option v-for="item in options.issueType" :value="item.key" :key="item.key" :label="item.value"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="OFFICE号" prop="issueOffice"
                              v-if="issueChannel === 'B2B' || issueChannel === 'BSP' ||issueChannel === 'BOP'">
                  <el-select v-model="detail.issueOffice" class="w160">
                    <el-option v-for="item in options.officeNo" :value="item.key" :key="item.key" :label="item.cname"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="支付方式" prop="payWay" v-if="issueChannel === 'B2C' || issueChannel === 'B2B'">
                  <el-select v-model="detail.payWay" class="w160" filterable>
                    <el-option v-for="item in options.payWay" :key="item.key" :value="item.key" :label="item.value"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="支付流水号" v-if="issueChannel === 'B2C' || issueChannel === 'B2B'">
                  <el-input v-model="detail.payNo" class="w160"/>
                </el-form-item>
                <el-form-item label="航司订单号" v-if="issueChannel === 'B2C' || issueChannel === 'B2B'">
                  <el-input v-model="detail.airlineOrderId" class="w160"/>
                </el-form-item>
              </div>
              <div>
                <el-form-item label="采购票面价" v-if="issueChannel === 'B2B' || issueChannel === 'BSP'">
                  <el-input size="mini" :value="offlineIssue.purchasePrintPrice" @input="onInputPurchasePrintPrice" class="w160"/>
                </el-form-item>
                <el-form-item label="代理费" v-if="issueChannel === 'B2B' || issueChannel === 'BSP'">
                <c-percent-input size="mini" :value="offlineIssue.agencyRate" @input="onInputAgencyRate" class="w160"/>
              </el-form-item>
                <el-form-item label="定额费" v-if="issueChannel === 'B2B' || issueChannel === 'BSP'">
                  <el-input size="mini" :value="offlineIssue.agencyFixedFee" @input="onInputAgencyFixedFee" class="w160"/>
                </el-form-item>
                <el-form-item label="采购总金额">
                  <el-input v-model="totalPurchase" class="w160" disabled>
                    <span slot="append">(含税)</span>
                  </el-input>
                </el-form-item>
                <el-form-item label="出票员">
                  <el-select v-model="detail.issueUser" class="w160">
                    <el-option v-for="item in options.issueUser" :key="item.key" :value="item.key" :label="item.value"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="出票账号" v-if="showIssueAccount">
                  <el-autocomplete
                    class="w160"
                    v-model="detail.issueAccount"
                    :fetch-suggestions="queryIssueAccountSearch"
                    placeholder="请输入账号"
                  />
                </el-form-item>
              </div>
            </template>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template v-else>
        <el-form ref="offlineIssueForm" inline label-width="100px" size="mini" :model="detail" :rules="rules">
          <div>
            <el-form-item label="出票渠道" prop="issueChannel">
              <el-select v-model="detail.issueChannel" class="w160">
                <el-option v-for="item in options.issueChannel" :value="item.key" :key="item.key" :label="item.cname"/>
              </el-select>
            </el-form-item>
            <el-form-item label="出票方" v-if="issueChannel === 'B2C'">
              <el-select v-model="detail.issueType" class="w160">
                <el-option v-for="item in options.issueType" :value="item.key" :key="item.key" :label="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="OFFICE号" prop="issueOffice"
                          v-if="issueChannel === 'B2B' || issueChannel === 'BSP' ||issueChannel === 'BOP'">
              <el-select v-model="detail.issueOffice" class="w160">
                <el-option v-for="item in options.officeNo" :value="item.key" :key="item.key" :label="item.cname"/>
              </el-select>
            </el-form-item>
            <el-form-item label="支付方式" prop="payWay" v-if="issueChannel === 'B2C' || issueChannel === 'B2B'">
              <el-select v-model="detail.payWay" class="w160" filterable>
                <el-option v-for="item in options.payWay" :key="item.key" :value="item.key" :label="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="支付流水号" v-if="issueChannel === 'B2C' || issueChannel === 'B2B'">
              <el-input v-model="detail.payNo" class="w160"/>
            </el-form-item>
            <el-form-item label="航司订单号" v-if="issueChannel === 'B2C' || issueChannel === 'B2B'">
              <el-input v-model="detail.airlineOrderId" class="w160"/>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="采购票面价" v-if="issueChannel === 'B2B' || issueChannel === 'BSP'">
              <el-input size="mini" :value="offlineIssue.purchasePrintPrice" @input="onInputPurchasePrintPrice" class="w160"/>
            </el-form-item>
            <el-form-item label="代理费" v-if="issueChannel === 'B2B' || issueChannel === 'BSP'">
              <c-percent-input size="mini" :value="offlineIssue.agencyRate" @input="onInputAgencyRate" class="w160"/>
            </el-form-item>
            <el-form-item label="定额费" v-if="issueChannel === 'B2B' || issueChannel === 'BSP'">
              <el-input size="mini" :value="offlineIssue.agencyFixedFee" @input="onInputAgencyFixedFee" class="w160"/>
            </el-form-item>
            <el-form-item label="采购总金额">
              <el-input v-model="totalPurchase" class="w160" disabled>
                <span slot="append">(含税)</span>
              </el-input>
            </el-form-item>
            <el-form-item label="出票员">
              <el-select v-model="detail.issueUser" class="w160">
                <el-option v-for="item in options.issueUser" :key="item.key" :value="item.key" :label="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="B2C账号" v-if="showIssueAccount">
              <el-autocomplete
                class="w160"
                v-model="detail.issueAccount"
                :fetch-suggestions="queryIssueAccountSearch"
                placeholder="请输入账号"
              />
            </el-form-item>
          </div>
        </el-form>
      </template>
    </el-card>

    <el-card class="card-bottom-spacing">
      <div style="text-align: center">
        <!--<easy-button type="primary" @click="onDrawTicket" v-if="canDrawTicket" class="w150">出票</easy-button>-->
        <easy-button :disabled="disabled" type="primary" @click="onFinishTicket" v-if="canFinishTicket" class="w120">已出票</easy-button>
        <easy-button :disabled="disabled" type="primary" @click="onThawTicket" v-if="canThawTicket" class="w120">已解冻</easy-button>
        <easy-button :disabled="disabled" type="danger" @click="onFailedTicket" v-if="canFailedTicket" class="w120">取消订单</easy-button>
        <el-button :disabled="disabled" type="success" @click="onChangePNR" v-if="canChangePNR" class="w120">
          {{detail.recordNo?'更换PNR':'订座'}}
        </el-button>
        <c-copy :disabled="disabled" :text="b2cMsg" v-if="canB2CTicket" type="primary" class="w120">B2C出票</c-copy>
        <easy-button :disabled="disabled" type="warning" @click="onSaveOrder" class="w120">保存</easy-button>
      </div>
    </el-card>

    <el-card class="card-bottom-spacing">
      <div slot="header" class="card-title">
        备注
      </div>
      <el-form label-width="60px" size="mini">
        <el-form-item label="原备注">
          <span class="font-red">{{detail.issueRemark}}</span>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            style="width: 1000px"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 8}"
          >
          </el-input>
        </el-form-item>
        <el-form-item label=" ">
          <el-button :disabled="!canSaveRemark" type="primary" @click="onSaveRemark">保存备注</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="card-bottom-spacing">
      <div slot="header" class="card-title">
        客户联系方式
      </div>
      <el-form size="mini" inline>
        <el-form-item label="姓名">
          <el-input v-model="detail.contactPerson" class="w160"/>
        </el-form-item>
        <el-form-item label="联系电话" label-width="120px">
          <el-input v-model="detail.contactNumber" class="w160"/>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px">
          <el-input v-model="detail.contactNumber" class="w160"/>
        </el-form-item>
      </el-form>
    </el-card>

    <el-collapse class="easy-ui-collapse">
      <el-collapse-item>
        <div slot="title" class="card-title">
          订单日志
        </div>
        <el-table
          :data="orderLog"
          border
          class="el-easy-ui-table">
          <el-table-column
            label="序号"
            type="index"
            width="40">
          </el-table-column>
          <el-table-column
            label="操作时间"
            min-width="90">
            <template slot-scope="scope">
              {{scope.row.operateTime | datetimeFormat}}
            </template>
          </el-table-column>
          <el-table-column
            prop="actionType"
            label="操作类型"
            min-width="80">
          </el-table-column>
          <el-table-column
            prop="operator"
            label="操作人"
            min-width="60">
          </el-table-column>
          <el-table-column
            prop="actionMsg"
            label="备注"
            min-width="300">
          </el-table-column>
          <!--el-table-column
            prop="operateDept"
            label="操作部门"
            min-width="100">
          </el-table-column-->
        </el-table>
      </el-collapse-item>
    </el-collapse>
    <component :is="dialog.tag" :data="dialog.data" @ok="refresh"
               @close="dialog.tag = ''" @change-pnr="$refs['onlineDrawTicket'].loadB2bList()"/>
  </l-content>
</template>

<script>
import user from '@mixins/user'
import Dict from '@/constants/Dict'
import OnlineDrawTicket from './comps/OrderIssueDetail/OnlineDrawTicket'
import ChangePnrDialog from './comps/OrderIssueDetail/ChangePnrDialog'
import CancelPnrDialog from './comps/OrderIssueDetail/CancelPnrDialog'

export default {
  mixins: [user],
  components: {
    ChangePnrDialog,
    OnlineDrawTicket,
    CancelPnrDialog
  },
  name: 'OrderIssueDetail',
  props: {
    app: {
      type: Object,
      default () {
        return {
          extra: {
            localOrderId: ''
          }
        }
      }
    }
  },
  data () {
    return {
      now: new Date(),
      loadCount: 0,
      activeTicketTab: 'online',
      options: {
        policyCodeMark: [],
        issueChannel: [],
        payWay: [],
        issueUser: [],
        issueType: [],
        issueAccount: [],
        officeNo: Dict.Options.officeNo
      },
      operator: {
        issueTicket: true
      },
      loaded: false,
      loading: true,
      checked: false,
      value: '',
      offlineIssue: {
        purchasePrintPrice: '',
        agencyRate: '',
        agencyFixedFee: ''
      },
      dialog: {
        tag: '',
        data: {}
      },
      detail: {
        canDoIssue: false,
        issueAccount: '',
        currOperator: null,
        canLock: null,
        localOrderId: null,
        adtk: null,
        policyTypeStr: null,
        airlineRecordNo: null,
        cancelIssueStatus: null,
        dataChangeCreater: null,
        dataChangeCreateTime: null,
        dataChangeLastTime: null,
        eiRemark: null,
        extOrderId: null,
        flightClass: null,
        issueBillId: null,
        issueRemark: null,
        issueStatus: null,
        lastPrintTicketTime: null,
        officeNo: null,
        issueOffice: '',
        orderDate: null,
        policyCode: null,
        policyId: null,
        policyType: null,
        recordNo: null,
        ticketType: null,
        urgency: null,
        urgeTimes: null,
        saleType: null,
        issueBillAssignOperator: null,
        intlRebookOrder: null,
        isVip: null,
        flightAgency: null,
        loadAccount: null,
        tbookingDatetime: null,
        realReservationType: null,
        currencyType: null,
        customerId: null,
        eEiRemark: null,
        specialCode: null,
        ownerAirline: null,
        fareBasis: null,
        ctripRcRule: null,
        flightWay: null,
        orderSource: null,
        shopName: null,
        shopCode: null,
        bookWay: null,
        bookWayStr: null,
        pnrText: null,
        oldPnr: null,
        oldAirlineRecordNo: null,
        lockOperatorName: '',
        lockOperator: null,
        lockTime: null,
        contactPerson: null,
        contactNumber: null,
        contactEmail: null,
        issueUser: null,
        issueTime: null,
        issueChannel: null,
        issueType: null,
        issueWay: null,
        protocolNo: null,
        payWay: null,
        payNo: null,
        airlineOrderId: null,
        agencyRate: null,
        totalPurchase: null,
        orderStatus: null,
        relaOrderId: null,
        updateTime: null,
        createTime: null,
        updateUser: null,
        createUser: null,
        tripInfoList: [],
        passengerList: [],
        receivablesList: []
      },
      selectRows: [],
      orderLog: [],
      form: {
        remark: ''
      },
      rules: {
        issueChannel: this.$checkRules.orderIssueDetail.issueChannel,
        issueOffice: this.$checkRules.orderIssueDetail.officeNo,
        payWay: this.$checkRules.orderIssueDetail.payWay,
        ticketNo: this.$checkRules.orderIssueDetail.ticketNo
      }
    }
  },
  watch: {
    'detail.issueChannel' () {
      this.loadIssueAccount()
    },
    'detail.issueType' () {
      this.loadIssueAccount()
    },
    'operator.issueTicket' () {
      if (this.loadCount > 0) {
        this.refresh()
      }
    }
  },
  computed: {
    disabled () {
      return !this.detail.canDoIssue
    },
    canSaveRemark () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return this.detail.canDoIssue || code === 'issueTicket' || code === 'refundAll' || code === 'refundPart' || code === 'issueFailed' || code === 'thawFailed'
    },
    totalPurchase () {
      return this.fixed2((+this.passengerListTotal[3]) + (+this.passengerListTotal[6]))
    },
    issueChannel () {
      const item = Dict.Map.issueChannel[this.detail.issueChannel]
      return item ? item.code : ''
    },
    passengerListTotal () {
      const list = this.detail.passengerList
      const purchasePrintPrice = list.reduce((sum, i) => {
        return sum + (parseFloat(i.purchasePrintPrice || 0) || 0)
      }, 0)
      const agencyFixedFee = list.reduce((sum, i) => {
        return sum + (parseFloat(i.agencyFixedFee || 0) || 0)
      }, 0)
      const purchasePrice = list.reduce((sum, i) => {
        return sum + (parseFloat(i.purchasePrice || 0) || 0)
      }, 0)
      const saleProfit = list.reduce((sum, i) => {
        return sum + (parseFloat(i.saleProfit || 0) || 0)
      }, 0)
      const salePrice = list.reduce((sum, i) => {
        return sum + (parseFloat(i.salePrice || 0) || 0)
      }, 0)
      const taxAndOilFee = list.reduce((sum, i) => {
        return sum + (parseFloat(i.tax || 0) || 0) + (parseFloat(i.oilFee || 0) || 0)
      }, 0)
      // const serviceFee = list.reduce((sum, i) => {
      //   return sum + (parseFloat(i.serviceFee || 0) || 0)
      // }, 0)
      // const insuranceFee = list.reduce((sum, i) => {
      //   return sum + (parseFloat(i.insuranceFee || 0) || 0)
      // }, 0)
      const issueProfit = list.reduce((sum, i) => {
        return sum + (parseFloat(i.issueProfit || 0) || 0)
      }, 0)
      const saleTotalPrice = list.reduce((sum, i) => {
        return sum + (parseFloat(i.saleTotalPrice || 0) || 0)
      }, 0)
      const fixed2 = this.fixed2
      return ['', fixed2(purchasePrintPrice), '', fixed2(agencyFixedFee), fixed2(purchasePrice), fixed2(saleProfit), fixed2(salePrice), fixed2(taxAndOilFee), fixed2(issueProfit), fixed2(saleTotalPrice)]
    },
    showUrgency () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'drawing' || code === 'waitTicket' || code === 'thawFailed'
    },
    isThawFailed () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'thawFailed'
    },
    canLock () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'waitTicket'
    },
    canUnlock () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'drawing'
    },
    canDrawTicket () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'waitTicket' || code === 'drawing'
    },
    canFinishTicket () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return (code === 'waitTicket' || code === 'drawing') && this.activeTicketTab === 'offline'
    },
    canThawTicket () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'thawFailed'
    },
    canFailedTicket () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return (code === 'waitTicket' || code === 'drawing') && this.activeTicketTab === 'offline'
    },
    canChangePNR () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'waitTicket' || code === 'drawing'
    },
    canOnlineIssue () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'waitTicket' || code === 'drawing'
    },
    canDismantle () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return (code === 'drawing') && this.detail.passengerList.length >= 2
    },
    canB2CTicket () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      // 只有当航司为KY 时才显示
      return (code === 'drawing') && this.detail.tripInfoList.length === 1 && this.detail.ownerAirline === 'KY'
    },
    b2cMsg () {
      if (this.canB2CTicket) {
        // B2C_DoTicket?local_order_id=4444&FlightStr=出发地|目的地|航班号|舱位|乘机日期|销售票面价&Psg=姓名1,身份证1|姓名2,身份证
        // B2C_DoTicket?local_order_id=4444&FlightStr=KMG|CKG|KY8295|M|2018-08-28|1000&Psg=彭伟林,430181198705123917|张散,NI372401198111192229
        const list = []
        const detail = this.detail
        const tripInfo = detail.tripInfoList[0]
        const passengers = detail.passengerList.map(i => i.passengerName + ',' + (i.cardNo || ''))
        const flightStrs = []

        flightStrs.push(tripInfo.dPort)
        flightStrs.push(tripInfo.aPort)
        flightStrs.push(tripInfo.flight)
        flightStrs.push(tripInfo.subClass)
        flightStrs.push(new Date(tripInfo.takeOffTime).format('yyyy-MM-dd'))
        flightStrs.push(0)

        list.push('local_order_id=' + detail.localOrderId)
        list.push('FlightStr=' + flightStrs.join('|'))
        list.push('Psg=' + passengers.join('|'))

        return 'B2C_DoTicket?' + list.join('&')
      } else {
        return ''
      }
    },
    showIssueAccount () {
      return this.detail.issueChannel === 'B2C'
    },
    lockTime () {
      const minute = (this.now.getTime() - this.detail.lockTime) / 60 / 1000
      if (minute < 60) {
        return minute.toFixed(0) + '分钟'
      } else if (minute < 60 * 24) {
        return (minute / 60).toFixed(0) + '小时'
      } else {
        return (minute / 24 / 60).toFixed(0) + '天'
      }
    },
    canSetTicketNo () {
      const code = Dict.Map.orderStatus[this.detail.orderStatus].code
      return code === 'drawing'
    }
  },
  filters: {
    cabinFilter (v) {
      const map = {
        F: '-头等舱',
        C: '-公务舱',
        Y: '-经济舱'
      }
      return map[v] || ''
    },
    leaveTimeFilter (val) {
      const minute = (val - new Date().getTime()) / 60 / 1000
      if (minute < 0) {
        return '已过期'
      } else if (minute < 60) {
        return minute.toFixed(0) + '分钟'
      } else if (minute < 60 * 24) {
        return (minute / 60).toFixed(0) + '小时'
      } else {
        return (minute / 24 / 60).toFixed(0) + '天'
      }
    }
  },
  created () {
    this.$dateUtils.getNow().then(now => {
      this.now = now
    })
    this.refresh()
    this.loadOptions()
    this.checkIsOutStatus()
  },
  methods: {
    queryIssueAccountSearch (v, cb) {
      cb(this.options.issueAccount)
    },
    loadIssueAccount () {
      if (this.showIssueAccount) {
        if ((this.options.issueAccount || []).length <= 0) {
          this.$service.order.loadB2cAccount({airline: this.detail.ownerAirline}).then(res => {
            this.options.issueAccount = res.data
          })
        }
      }
    },
    checkIsOutStatus () {
      let timer = null
      this.operator.issueTicket = true
      const check = () => {
        this.$service.order.checkIsOutStatus({localOrderId: this.app.extra.localOrderId}).then(res => {
          this.operator.issueTicket = res.data.isOutStatus
          if (this.operator.issueTicket) {
            this.loadCount++
            timer = setTimeout(check, 5000)
          } else {
            clearTimeout(timer)
            this.loadCount = 0
          }
        })
      }
      check()
    },
    onInputPurchasePrintPrice (v) {
      this.offlineIssue.purchasePrintPrice = v
      // 改变列表中的值
      this.detail.passengerList.forEach(item => {
        item.purchasePrintPrice = v
        item.purchasePrice = v ? this.fixed2(v * (1 - (item.agencyRate || 0))) : ''
        item.issueProfit = v ? this.fixed2(item.salePrice - item.purchasePrice) : ''
      })
    },
    onInputAgencyRate (v) {
      const fixed2 = this.fixed2
      this.offlineIssue.agencyRate = v
      this.detail.passengerList.forEach(item => {
        item.agencyRate = v
        item.agencyFixedFee = v ? fixed2(parseFloat(v) * item.purchasePrintPrice) : ''
        item.purchasePrice = fixed2(item.purchasePrintPrice - (item.agencyFixedFee || 0))
        item.issueProfit = fixed2(item.salePrice - item.purchasePrice)
      })
    },
    onInputAgencyFixedFee (v) {
      const fixed2 = this.fixed2
      const fixed4 = this.fixed4
      this.offlineIssue.agencyFixedFee = v
      this.detail.passengerList.forEach(item => {
        item.agencyFixedFee = v
        item.agencyRate = v ? fixed4(v / item.purchasePrintPrice) : ''
        item.purchasePrice = fixed2(item.purchasePrintPrice - (item.agencyFixedFee || 0))
        item.issueProfit = fixed2(item.salePrice - item.purchasePrice)
      })
    },
    loadOptions () {
      this.$service.options.getYeePayAccountType().then(res => {
        this.options.payWay = res.data
      })
      this.$service.airOnlineShop.loadIssueUserOption().then(res => {
        this.options.issueUser = res.data
      })
      this.$service.options.getSupply().then(res => {
        this.options.issueType = res.data
      })
      this.$service.options.getIssueChannel().then(res => {
        this.options.issueChannel = res.data
      })
      this.$service.options.getPolicyCodeMark().then(res => {
        this.options.policyCodeMark = res.data
      })
    },
    fixed2 (v) {
      return v ? ('' + (+v.toFixed(2))) : ''
    },
    fixed4 (v) {
      return v ? ('' + (+v.toFixed(4))) : ''
    },
    getSummaries (param) {
      const {columns} = param
      if (columns.length > 0) {
        columns[0].colSpan = 4
        return ['合计', ...this.passengerListTotal]
      }
    },
    refresh () {
      this.loadOrderDetail()
      this.loadOrderLog()
    },
    loadOrderDetail () {
      this.loading = true
      this.$service.order.detailIssueOrder({localOrderId: this.app.extra.localOrderId}).then(res => {
        this.detail = res.data
        this.detail.issueOffice = this.detail.issueOffice || 'CSX510'
        this.detail.issueUser = this.detail.issueUser || this.detail.currOperator
        this.loaded = true
      }).finally(() => {
        this.loading = false
      })
    },
    loadOrderLog () {
      this.$service.order.queryOrderLogList({localOrderId: this.app.extra.localOrderId}).then(res => {
        this.orderLog = res.data
      })
    },
    onUnlock (done) {
      if (this.detail.canDoIssue) {
        this.unLock(done)
      } else {
        this.$confirm('该订单已被' + this.detail.lockOperatorName + '锁单, 是否确认解锁？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.unLock(done)
        }).catch(done)
      }
    },
    unLock (done) {
      this.$service.order.deblockingIssueOrder({
        localOrderId: this.detail.localOrderId
      }).then(() => {
        this.detail.canDoIssue = false
        this.detail.orderStatus = Dict.getByCode('orderStatus', 'waitTicket').key
        this.loadOrderLog()
      }).finally(done)
    },
    onLock (done) {
      this.$service.order.lockIssueOrder({
        localOrderId: this.detail.localOrderId
      }).then(() => {
        this.detail.canDoIssue = true
        this.detail.orderStatus = Dict.getByCode('orderStatus', 'drawing').key
        this.detail.lockOperatorName = this.userInfo.realName
        this.$dateUtils.getNow().then(now => {
          this.now = now
          this.detail.lockTime = now.getTime()
        })
        this.loadOrderLog()
      }).finally(done)
    },
    onSaveRemark () {
      this.$service.order.updateAirOrderRemark({
        localOrderId: this.detail.localOrderId,
        remark: this.form.remark
      }).then(() => {
        this.refresh()
      })
    },
    onSaveOrder (done) { // 保存
      this.$refs['offlineIssueForm'].validate(valid => {
        if (valid) {
          this.$confirm('是否确认保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$service.order.saveOrder(this.detail).then(() => {
              this.refresh()
            }).finally(done)
          }).catch(done)
        } else {
          done()
        }
      })
    },
    onDrawTicket (done) { // 出票
      this.$confirm('是否确认出票？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$service.order.drawTicket(this.detail).then(() => {
          this.refresh()
        }).finally(done)
      }).catch(done)
    },
    onFinishTicket (done) { // 已出票
      this.$refs['offlineIssueForm'].validate(valid => {
        if (valid) {
          this.$refs['passengerList'].validate(valid => {
            if (valid) {
              this.$confirm('是否确认已出票？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$service.order.finishTicket(this.detail).then(() => {
                  this.refresh()
                  if (this.detail.issueChannel === 'B2C' || this.detail.issueChannel === 'OTHER') {
                    this.dialog.data = {
                      title: '已出票，是否取消PNR？',
                      localOrderId: this.detail.localOrderId,
                      pnr: this.detail.oldPnr
                    }
                    this.dialog.tag = 'CancelPnrDialog'
                  }
                }).finally(done)
              }).catch(done)
            } else {
              this.$message.error('校验未通过')
              done()
            }
          })
        } else {
          this.$message.error('校验未通过')
          done()
        }
      })
    },
    onFailedTicket (done) { // 取消订单
      this.$confirm('是否确认取消订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$service.order.failedTicket(this.detail).then(() => {
          this.refresh()
        }).finally(done)
      }).catch(done)
    },
    onChangePNR () { // 更换PNR
      this.dialog.data = this.detail
      this.dialog.tag = 'ChangePnrDialog'
    },
    onInputTicketNo (idx, v) {
      this.detail.passengerList[idx].ticketNoAll = v
      this.$nextTick(() => {
        const str = v.replace(/-/g, '')
        if (str.length > 3) {
          const no1 = str.substring(0, 3)
          const no2 = str.substring(3)
          if (idx === 0) {
            const reg = no2.match(/\d+$/)
            if (!reg) {
              this.detail.passengerList.forEach((item, idx) => {
                item.ticketNoAll = no1 + '-' + no2
              })
            } else {
              const no2Str = no2.substring(0, reg.index)
              const no2Num = +no2.substring(reg.index)
              this.detail.passengerList.forEach((item, idx) => {
                item.ticketNoAll = no1 + '-' + no2Str + (no2Num + idx)
              })
            }
          } else {
            this.detail.passengerList[idx].ticketNoAll = no1 + '-' + no2
          }
        } else if (idx === 0) {
          this.detail.passengerList.forEach(item => {
            item.ticketNoAll = v
          })
        }
      })
    },
    // 拆单
    onDismantle (done) {
      // 复制一份详情
      const form = Object.assign({}, this.detail)
      form.passengerList = this.selectRows
      if (this.selectRows.length <= 0) {
        this.$alert('请选择乘机人', '提示')
        done()
        return
      }
      if (this.selectRows.length === this.detail.passengerList.length) {
        this.$alert('请至少留下一个乘客在该订单', '提示')
        done()
        return
      }
      this.$confirm('是否确认拆单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$service.order.dismantleOrder(form).then(res => {
          this.refresh()
          window.open('#/air-order-manage/order-issue-detail?localOrderId=' + res.data.localOrderId)
        }).finally(done)
      }).catch(done)
    },
    onThawTicket (done) {
      // 已解冻操作
      this.$confirm('是否确认已解冻？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$service.order.thawOrder({localOrderId: this.detail.localOrderId}).then(() => {
          this.refresh()
        }).finally(done)
      }).catch(done)
    },
    onCancelPNR () {
      this.dialog.data = {
        title: '取消PNR',
        localOrderId: this.detail.localOrderId,
        pnr: this.detail.oldPnr
      }
      this.dialog.tag = 'CancelPnrDialog'
    },
    onSetTicketNo (done) {
      this.$service.order.supplementOrder({type: 1, pnrCode: this.detail.recordNo}).then(res => {
        const ticketNoMap = {};
        (res.data.passengerList || []).forEach(passenger => {
          ticketNoMap[passenger.passengerName] = passenger.ticketNo
        })
        this.detail.passengerList.forEach(passenger => {
          passenger.ticketNoAll = ticketNoMap[passenger.passengerName]
        })
      }).finally(done)
    }
  }
}
</script>

<style scoped>
.msg-label {
}

.msg-content {
  color: #999999;
}

.msg-row {
  line-height: 35px;
}

.msg-span {
  display: inline-block;
  margin-right: 10px;
}

.trip-mark {
  background-color: #379be9;
  color: white;
  display: inline-block;
  position: relative;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
}

.trip-mark:after {
  content: "";
  width: 0;
  height: 0;
  position: absolute;
  left: 30px;
  top: 12px;
  border-top: solid 3px transparent;
  border-left: solid 3px #379be9;
  border-bottom: solid 3px transparent;
}

.trip-row {
  background-color: #f9f9f9;
  padding: 0 10px;
  margin-bottom: 10px;
}

.trip-part-1 {
  line-height: 50px;
  width: 50px;
  display: inline-block;
  vertical-align: text-top;
}

.trip-part-2, .trip-part-4 {
  width: 420px;
  display: inline-block;
  vertical-align: text-top;
}

.trip-part-2 .trip-content, .trip-part-4 .trip-content {
  height: 25px;
  line-height: 50px;
}

.trip-part-3 {
  font-size: 24px;
  color: #379be9;
  line-height: 50px;
  display: inline-block;
  vertical-align: text-top;
  padding-left: 10px;
  padding-right: 80px;
}

.trip-part-5, .trip-part-6, .trip-part-7 {
  line-height: 50px;
  width: 150px;
  display: inline-block;
  vertical-align: text-top;
}

</style>
